package com.mirama.framework.rabbitmq;


import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Slf4j
@Component
public class MqSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @PostConstruct
    public void rabbitTemplateInit() {

        // 开启returncallback yml 需要 配置 publisher-returns: true
        // 实现ReturnCallback
        // 当消息发送出去找不到对应路由队列时，将会把消息退回
        // 如果有任何一个路由队列接收投递消息成功，则不会退回消息
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            log.info("消息被退回: {}, {} {} {} {}", new String(message.getBody()), replyCode, replyText, exchange, routingKey);
        });

        // 消息确认 yml 需要配置  publisher-returns: true
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                log.info("消息发送成功,id: {}", correlationData == null ? "" : correlationData.getId());
            } else {
                log.info("消息发送到失败,原因: {}", cause);
            }
        });
    }
}
